﻿using ezCloud.Api.Models;
using ezCloud.Data;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Web.Http.ModelBinding;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;

using ezCloud.Api.Providers;
using ezCloud.Api.Results;
using System.Data.SqlTypes;
using ezCloud.Api.Common;
using System.Data.SqlClient;
using System.Data;
using System.Data.Linq;
using System.Reflection;
using System.Data.Linq.Mapping;
using System.Collections.ObjectModel;

namespace ezCloud.Api.Controllers
{
    [RoutePrefix("api/Hotel")]
    public class HotelController : ezController
    {
        private ApplicationUserManager _userManager;

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("GetCurrentHotel")]
        public IHttpActionResult getCurrentHotel()
        {
            var user = Common.UserUtitily.getUserProfile();
            var currentHotel = context.Hotels.Where(htl => htl.HotelId == user.HotelId).FirstOrDefault();
            if (currentHotel!=null)
            {
                //var currentHotelDefaultDiscount = currentHotel.EzHotelDefaultDiscountsList.ToList();
                var currentHotelModule = currentHotel.EzHotelModulesList.Where(module => module.Status == true).ToList();
                foreach (var hotelModule in currentHotelModule)
                {
                    var module = hotelModule.EzModules;
                }
                var currentHotelDefaultDiscount = currentHotel.EzHotelDefaultDiscountsList.ToList();
                foreach (var discount in currentHotelDefaultDiscount)
                {
                    var moduleDiscount = discount.EzDefaultDiscounts.EzModules;
                }
                var currentHotelPaymentLogs = currentHotel.EzPaymentLogsList.Where(log => log.LogKey == "NEW_PAYMENT");
                var ezReferralProgramCode = currentHotel.EzReferralCodesList.FirstOrDefault();
            }
           
            return Ok(currentHotel);
        }
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("GetCurrentHotelConnectivities")]
        public async Task<IHttpActionResult> GetCurrentHotelConnectivities()
        {
            var currentUser = Common.UserUtitily.getUserProfile();
            var currentHotel = context.Hotels.FirstOrDefault(htl => htl.HotelId == currentUser.HotelId);
            //var connectivities = context.HotelConnectivityModuleConfig.Where(htl => htl.HotelId == currentUser.HotelId).ToList();
            
            var Hotelconnectivities = new HotelConnectivity();
            if (currentHotel!=null)
            {
                if (currentHotel.EzHotelModulesList.FirstOrDefault(hm => hm.EzModules.ModuleCode == "SMARTCARD" && hm.Status == true) != null)
                {

                    var connectivities = currentHotel.HotelConnectivityModuleConfigList;
                    if (connectivities.Count() > 0)
                    {
                        Hotelconnectivities.isUsed = true;
                        Hotelconnectivities.IsInputCardToCheckout = connectivities.First().IsInputCardToCheckout == null ? false : connectivities.First().IsInputCardToCheckout.Value;
                    }
                    else
                    {
                        Hotelconnectivities.isUsed = false;
                        Hotelconnectivities.IsInputCardToCheckout = false;
                    }

                }
                else
                {
                    Hotelconnectivities.isUsed = false;
                    Hotelconnectivities.IsInputCardToCheckout = false;
                }
            }
            
            return Ok(Hotelconnectivities);
        }
       
        //GET api/Hotel/GetHotelList        
        [Route("GetAllHotels")]
        public async Task<IHttpActionResult> GetAllHotels()
        {


            return Ok(context.Hotels.ToList());


        }
        //GET api/Hotel/GetHotelList
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("GetHotelList")]
        public List<Hotels> GetHotelList()
        {

            var currentClientUser = Common.UserUtitily.getUserProfile();

            return context.Hotels.Where(hotel => hotel.HotelOwnerId == currentClientUser.UserId && hotel.IsActive).ToList();


        }

        //GET api/Hotel/GetHotelList
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("GetHotelLists")]
        public async Task<IHttpActionResult> GetHotelLists()
        {

            var currentClientUser = Common.UserUtitily.getUserProfile();

            var tmp = new { hotels = context.Hotels.Where(hotel => hotel.HotelOwnerId == currentClientUser.UserId).ToList() };
            return Ok(tmp);

        }


        

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("GetCurrentUserHotel")]
        public Hotels GetCurrentUserHotel()
        {

            var currentClientUser = Common.UserUtitily.getUserProfile();

            //return context.Hotels.Where(hotel => hotel.HotelOwnerId == currentClientUser.UserId).ToList();

            Hotels hotel = context.Hotels.Where(htl => htl.HotelId == currentClientUser.HotelId).FirstOrDefault();
            if (hotel == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return hotel;


        }

        public class ResetHotelDataModel
        {
            public int HotelId { get; set; }
            public bool IsDeleteAllConfig { get; set; }
            public bool IsDeleteAllCustomer { get; set; }
        }

        public List<String> GetAllTablesRelated(string tableName)
        {
            List<String> result = new List<String>();
            DataSet ds = new DataSet();
            DataTable hotelRelatedTables = new DataTable();
            string ConnectionString =  System.Configuration.ConfigurationManager.ConnectionStrings["EzCloudConnectionString"].ToString();
            using (SqlConnection conn = new SqlConnection(ConnectionString))
            //using (SqlConnection conn = context.Connection.)
            {
            SqlCommand sqlComm = new SqlCommand("dbo.GetAllHotelRelatedTable", conn);
                sqlComm.Parameters.AddWithValue("@TableName", tableName);
                sqlComm.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = sqlComm;
                da.Fill(ds);
                hotelRelatedTables = ds.Tables[0];
                foreach (DataRow r in hotelRelatedTables.Rows)
                {
                    result.Add(r["Parent table"].ToString());
                }
            }
            return result;
        }

        public void DeleleTable(string tableName,bool hasHotelId, int hotelId)
        {
            if (hasHotelId)
            {
                context.ExecuteCommand("delete from " + tableName + " where hotelid = " + hotelId);
            }
            else
            {
                context.ExecuteCommand("delete t from " + tableName + " t INNER JOIN ReservationRooms r ON t.ReservationRoomId=r.ReservationRoomId WHERE r.HotelId=" + hotelId);
            }
            
        }
        public List<String> RemoveFromList(List<String> mainList, List<String> subList)
        {
            //List<String> result = new List<string>();
            if (subList.Count > 0)
            {
                foreach (string str in subList)
                {
                    if (mainList.Contains(str))
                    {
                        mainList.Remove(str);
                    }
                }
            }
            return mainList;
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("ResetHotelData")]
        public async Task<IHttpActionResult> ResetHotelData(ResetHotelDataModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var user = Common.UserUtitily.getUserProfile();
            var currentHotel = context.Hotels.Where(htl => htl.HotelId == model.HotelId).FirstOrDefault();
            // Table Deleted Level 3 - With HotelId
            var tableDeleted_Level3 = new List<String>();
            tableDeleted_Level3.Add("RoomExtraServiceItems");
            tableDeleted_Level3.Add("POSPaymentTravellerPayments");
            
            //tableDeleted_Level3.Add("ExtraServiceItems");
            //tableDeleted_Level3.Add("ExtraServiceCategories");
            tableDeleted_Level3.Add("SystemInvoiceNumber");
            tableDeleted_Level3.Add("ReservationTravellerExtraInformation");
            tableDeleted_Level3.Add("NightAuditItems");
          
            if (tableDeleted_Level3.Count > 0)
            {
                foreach (var tableName in tableDeleted_Level3)
                {
                    DeleleTable(tableName, true, model.HotelId);
                }
            }

            // Table Deleted Level 3 - No HotelId
            var tableDeleted_Level3_NoHotelId = new List<String>();
            tableDeleted_Level3_NoHotelId.Add("ReportItems");
            tableDeleted_Level3_NoHotelId.Add("ReservationTravellers");
           
            if (tableDeleted_Level3_NoHotelId.Count > 0)
            {
                foreach (var tableName in tableDeleted_Level3_NoHotelId)
                {
                    DeleleTable(tableName, false, model.HotelId);
                }
            }

            // Table Deleted Level 2 - With HotelId
            var tableDeleted_Level2 = GetAllTablesRelated("ReservationRooms");
            tableDeleted_Level2 = RemoveFromList(tableDeleted_Level2, tableDeleted_Level3);
            tableDeleted_Level2 = RemoveFromList(tableDeleted_Level2, tableDeleted_Level3_NoHotelId);

            if (tableDeleted_Level2.Count > 0)
            {
                foreach (var tableName in tableDeleted_Level2)
                {
                    //if (tableName == "Payments")
                    //{
                    //    context.ExecuteCommand("delete from Payments where hotelid=" + model.HotelId + " and PaymentTypeName <> 'DELETED'");
                    //}
                    DeleleTable(tableName, true, model.HotelId);
                }
            }

            tableDeleted_Level2 = GetAllTablesRelated("POSPaymentTravellers");
            tableDeleted_Level2 = RemoveFromList(tableDeleted_Level2, tableDeleted_Level3);
            tableDeleted_Level2 = RemoveFromList(tableDeleted_Level2, tableDeleted_Level3_NoHotelId);

            if (tableDeleted_Level2.Count > 0)
            {
                foreach (var tableName in tableDeleted_Level2)
                {
                    //if (tableName == "Payments")
                    //{
                    //    context.ExecuteCommand("delete from Payments where hotelid=" + model.HotelId + " and PaymentTypeName <> 'DELETED'");
                    //}
                    DeleleTable(tableName, true, model.HotelId);
                }
            }

            // Table Deleted Level 1
            var tableDeleted_Level1 = new List<String>();

            tableDeleted_Level1 = GetAllTablesRelated("Hotels");
            tableDeleted_Level1 = RemoveFromList(tableDeleted_Level1, tableDeleted_Level3);
            tableDeleted_Level1 = RemoveFromList(tableDeleted_Level1, tableDeleted_Level3_NoHotelId);
            tableDeleted_Level1 = RemoveFromList(tableDeleted_Level1, tableDeleted_Level2);
            if (!model.IsDeleteAllConfig)
            {
                tableDeleted_Level1.Clear();
                //tableDeleted_Level1.Add("ExtraServiceItems");
                //tableDeleted_Level1.Add("ExtraServiceCategories");
                tableDeleted_Level1.Add("POSPaymentTravellers");
                tableDeleted_Level1.Add("ReservationRooms");
                tableDeleted_Level1.Add("Reservations");
                tableDeleted_Level1.Add("RoomRepair");
                tableDeleted_Level1.Add("Travellers");
                tableDeleted_Level1.Add("UserHotels");
            }
            else
            {
                DeleleTable("ExtraServiceItems", true, model.HotelId);
                DeleleTable("ExtraServiceCategories", true, model.HotelId);
                tableDeleted_Level1.Remove("ExtraServiceItems");
                tableDeleted_Level1.Remove("ExtraServiceCategories");
                tableDeleted_Level1.Add("Floors");
            }

            if (!model.IsDeleteAllCustomer)
            {
                tableDeleted_Level1.Remove("Travellers");
            }



            if (tableDeleted_Level1.Count > 0)
            {
                foreach (string tableName in tableDeleted_Level1)
                {
                    DeleleTable(tableName, true, model.HotelId);
                }
            }

            //update HouseStatus

            var rooms = context.Rooms.Where(h => h.HotelId == model.HotelId);
            foreach (var item in rooms)
            {
                item.HouseStatus = null;
            }
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);
            return Ok(new
            {
                Level3 = tableDeleted_Level3,
                Level3_NoHotelId = tableDeleted_Level3_NoHotelId,
                Level2 = tableDeleted_Level2,
                Level1 = tableDeleted_Level1
            });
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("HotelQuickSettings")]
        public async Task<IHttpActionResult> HotelQuickSettings(HotelViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var currentClientUser = Common.UserUtitily.getUserProfile();

            if (model.ezCloudSubDomain != null)
            {

                var subDomainHotel = context.Hotels.Where(htl => htl.EzCloudSubdomain == model.ezCloudSubDomain && htl.HotelId != model.HotelId && htl.IsActive).FirstOrDefault();

                if (subDomainHotel != null)
                {
                    ModelState.AddModelError("Message", "SUB_DOMAIN_HAS_BEEN_ALREADY_TAKEN");
                    return BadRequest(ModelState);
                }
            }

            //Tạo mới khách sạn
            Hotels hotel = new Data.Hotels();
            hotel.HotelEmail = model.HotelEmail;
            hotel.HotelName = model.HotelName;
            hotel.HotelAddress = model.HotelAddress;
            hotel.HotelPhone = model.HotelPhone;
            hotel.EzCloudSubdomain = model.ezCloudSubDomain;
            hotel.HotelDomain = model.HotelDomain;
            hotel.HotelWebsite = model.HotelWebsite;
            hotel.HotelLogoUrl = model.HotelLogoUrl;
            hotel.HotelSizeId = model.HotelSizeId;
            hotel.IsActive = model.isActive;
            hotel.ExpireDate = DateTime.UtcNow.AddDays(30);
            hotel.FullDayCheckoutTime = new TimeSpan(12, 0, 0);
            hotel.FullDayCheckinTime = new TimeSpan(12, 0, 0);
            hotel.TimeInPrivate = new TimeSpan(14, 0, 0);
            hotel.TimeOutPrivate = new TimeSpan(12, 0, 0);
            hotel.DayNightStartTime = new TimeSpan(21, 0, 0);
            hotel.DayNightEndTime = new TimeSpan(12, 0, 0);
            hotel.NightAuditTime = new TimeSpan(0, 0, 0);
            hotel.CreatedDate = DateTime.UtcNow;
            hotel.ExpireDate = hotel.CreatedDate.HasValue ? hotel.CreatedDate.Value.AddMonths(3) : (DateTime?)null;
            hotel.IsRoomDirtyAfterNighAudit = true;

            /* foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
             {
                 if (z.BaseUtcOffset.TotalMinutes == model.TimeZoneOffset)
                 {
                     hotel.TimeZoneId = z.Id;
                 }
             }*/
            //hotel.TimeZoneId = "SE Asia Standard Time";
            //hotel.TimeZoneOffset
            //hotel.TimeZoneId = model.TimeZoneId;
            //hotel.TimeZoneOffset = model.TimeZoneOffset;
            // hotel.TimeZoneId = "SE Asia Standard Time";
            //hotel.TimeZoneOffset = 420;
            hotel.TimeZoneId = model.TimeZoneId;
            var offSet = TimeZoneInfo.FindSystemTimeZoneById(model.TimeZoneId);
            hotel.TimeZoneOffset = (int)offSet.BaseUtcOffset.TotalMinutes;

            var user = UserManager.FindByName(currentClientUser.UserName);
            hotel.HotelOwnerId = currentClientUser.UserId;
            context.Hotels.InsertOnSubmit(hotel);
            hotel.RemainingDays = 0;
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            //Gán lại defaultHotelId cho User
            user.DefaultHotelId = hotel.HotelId;
            UserManager.Update(user);
            //Tạo tầng 
            var listFloor = new List<Floors>();
            for (int i = 0; i < model.HotelFloorNum; i++)
            {
                Floors floor = new Floors();
                floor.CreatedDate = DateTime.UtcNow;
                floor.CreatedUserId = currentClientUser.UserId;
                floor.HotelId = hotel.HotelId;
                floor.OrderNumber = (i + 1);
                floor.IsDeleted = false;
                floor.IsActive = true;
                floor.FloorName = "FLOOR " + (i + 1).ToString();
                listFloor.Add(floor);
            };
            context.Floors.InsertAllOnSubmit(listFloor);
            //Tạo loại phòng mặc định (Standard Room)
            RoomTypes standardRoomType = new Data.RoomTypes();
            standardRoomType.RoomTypeName = "STANDARD_ROOM";
            standardRoomType.RoomTypeCode = "STD";
            standardRoomType.RoomTypeDescription = "STANDARD_ROOM";
            standardRoomType.HotelId = hotel.HotelId;
            standardRoomType.DefaultAdults = 1;
            standardRoomType.DefaultChilds = 0;
            standardRoomType.Price = model.HotelRoomDefaultPrice;
            context.RoomTypes.InsertOnSubmit(standardRoomType);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            //Tạo Danh sách phòng mặc định
            var listRoom = new List<Rooms>();
            for (int i = 0; i < model.HotelFloorNum; i++)
            {
                var floor = listFloor[i];
                for (int j = 0; j < model.HotelRoomNumPerFloor; j++)
                {
                    Rooms room = new Rooms();
                    //room.RoomLocation = "FLOOR " + (i + 1);
                    if(floor.FloorId != null)
                    {
                        room.FloorId = floor.FloorId;
                    }
                    room.RoomDescription = "ROOM " + (i + 1) + "0" + (j + 1);
                    room.HotelId = hotel.HotelId;
                    room.RoomTypeId = standardRoomType.RoomTypeId;
                    room.HouseStatus = null;
                    if (j < 9)
                    {
                        room.RoomName = (i + 1) + "0" + (j + 1);
                    }
                    else
                    {
                        room.RoomName = (i + 1).ToString() + (j + 1).ToString();
                    }
                    room.CreatedDate = DateTime.UtcNow;
                    room.CreatedUserId = user.Id;
                    room.Priority = listRoom.Count;
                    listRoom.Add(room);
                    //context.Rooms.InsertOnSubmit(room);
                }
            }
            context.Rooms.InsertAllOnSubmit(listRoom);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            //Tạo extra service types mặc định
            string[] esTypesName = new string[] {
                                                    "MINIBAR",
                                                    "LAUNDRY",
                                                    "EXTRA_ROOM_CHARGE",
                                                    "COMPENSATION",
                                                    "EXTRA_SERVICES"
                                                };
            string[] esTypesDescription = new string[] {
                                                            "Minibar",
                                                            "Laundry",
                                                            "ExtraRoomCharge",
                                                            "Compensation",
                                                            "ExtraServices"
                                                       };

            List<List<string>> esCategoryName = new List<List<string>>();
            List<List<string>> esCategoryDescription = new List<List<string>>();
            //MiniBar
            List<string> miniBarCategoryName = new List<String> { "DRINK", "FOOD" };
            esCategoryName.Add(miniBarCategoryName);
            List<string> miniBarCategoryDescription = new List<String> { "DRINK", "FOOD" };
            esCategoryDescription.Add(miniBarCategoryDescription);

            //Laundry
            List<string> laundryCategoryName = new List<String> { "LAUNDRY_1", "LAUNDRY_2" };
            esCategoryName.Add(laundryCategoryName);
            List<string> laundryCategoryDescription = new List<String> { "LAUNDRY_1", "LAUNDRY_2" };
            esCategoryDescription.Add(laundryCategoryDescription);


            //ExtraRoomCharge
            List<string> extraRoomChargeCategoryName = new List<String> { "EXTRA_ROOM_CHARGE_1", "EXTRA_ROOM_CHARGE_2" };
            esCategoryName.Add(extraRoomChargeCategoryName);
            List<string> extraRoomChargeCategoryDescription = new List<String> { "EXTRA_ROOM_CHARGE_1", "EXTRA_ROOM_CHARGE_2" };
            esCategoryDescription.Add(extraRoomChargeCategoryDescription);

            //Compensation
            List<string> compensationCategoryName = new List<String> { "COMPENSATION_1", "COMPENSATION_2" };
            esCategoryName.Add(compensationCategoryName);
            List<string> compensationCategoryDescription = new List<String> { "COMPENSATION_1", "COMPENSATION_2" };
            esCategoryDescription.Add(compensationCategoryDescription);

            //ExtraServies
            /* List<string> extraServiesCategoryName = new List<String> { "EXTRA_SERVICE_1", "EXTRA_SERVICE_2" };
             esCategoryName.Add(extraServiesCategoryName);
             List<string> extraServiesCategoryDescription = new List<String> { "EXTRA_SERVICE_1", "EXTRA_SERVICE_2" };
             esCategoryDescription.Add(extraServiesCategoryDescription);*/
            List<string> extraServiesCategoryName = new List<String>();
            esCategoryName.Add(extraServiesCategoryName);
            List<string> extraServiesCategoryDescription = new List<String>();
            esCategoryDescription.Add(extraServiesCategoryDescription);

            for (int i = 0; i < esTypesName.Length; i++)
            {
                ExtraServiceTypes esTypes = new Data.ExtraServiceTypes();
                esTypes.ExtraServiceTypeName = esTypesName[i];
                esTypes.ExtraServiceDescription = esTypesDescription[i];
                esTypes.HotelId = hotel.HotelId;
                context.ExtraServiceTypes.InsertOnSubmit(esTypes);
                context.SubmitChanges();
                Common.Elastic.IndexLastAudit(context);
                if (i < esCategoryName.Count)
                {
                    List<string> categoriesNameByTypes = new List<string>(esCategoryName[i]);
                    List<string> categoriesDescriptionByTypes = new List<string>(esCategoryDescription[i]);
                    for (int j = 0; j < categoriesNameByTypes.Count; j++)
                    {
                        ExtraServiceCategories esCategories = new Data.ExtraServiceCategories();
                        esCategories.ExtraServiceCategoryName = categoriesNameByTypes[j];
                        esCategories.ExtraServiceCategoryDescription = categoriesDescriptionByTypes[j];
                        esCategories.ExtraServiceTypeId = esTypes.ExtraServiceTypeId;
                        esCategories.HotelId = hotel.HotelId;
                        context.ExtraServiceCategories.InsertOnSubmit(esCategories);
                        context.SubmitChanges();
                        Common.Elastic.IndexLastAudit(context);
                    }
                }

            }

            //Default System Settings
            Money defaultMoney = new Data.Money();
            var currency = context.Currencies.Where(curr => curr.CurrencyId == model.CurrencyId).FirstOrDefault();
            if (currency != null)
            {
                defaultMoney.MoneyName = currency.AlphabeticCode;
                defaultMoney.ExchangeRate = 1.00;
                defaultMoney.HotelId = hotel.HotelId;
                defaultMoney.CurrencyId = currency.CurrencyId;
                context.Money.InsertOnSubmit(defaultMoney);
                context.SubmitChanges();
                Common.Elastic.IndexLastAudit(context);
                hotel.DefaultMoneyId = defaultMoney.MoneyId;
            }
            

            StatusColors availableSC = new Data.StatusColors();
            availableSC.StatusCode = "AVAILABLE";
            availableSC.ColorCode = "#43A047";
            availableSC.HotelId = hotel.HotelId;
            availableSC.DefaultColorCode = "#43A047";
            context.StatusColors.InsertOnSubmit(availableSC);

            StatusColors bookedSC = new Data.StatusColors();
            bookedSC.StatusCode = "BOOKED";
            bookedSC.ColorCode = "#1E88E5";
            bookedSC.HotelId = hotel.HotelId;
            bookedSC.DefaultColorCode = "#1E88E5";
            context.StatusColors.InsertOnSubmit(bookedSC);

            StatusColors checkInSC = new Data.StatusColors();
            checkInSC.StatusCode = "CHECKIN";
            checkInSC.ColorCode = "#EF5350";
            checkInSC.HotelId = hotel.HotelId;
            checkInSC.DefaultColorCode = "#EF5350";
            context.StatusColors.InsertOnSubmit(checkInSC);

            StatusColors checkOutSC = new Data.StatusColors();
            checkOutSC.StatusCode = "CHECKOUT";

            checkOutSC.ColorCode = "#EE82EE";
            checkOutSC.HotelId = hotel.HotelId;
            checkOutSC.DefaultColorCode = "#EE82EE";
            context.StatusColors.InsertOnSubmit(checkOutSC);

            StatusColors cancelledSC = new Data.StatusColors();
            cancelledSC.StatusCode = "CANCELLED";
            cancelledSC.ColorCode = "#808080";
            cancelledSC.HotelId = hotel.HotelId;
            cancelledSC.DefaultColorCode = "#808080";
            context.StatusColors.InsertOnSubmit(cancelledSC);

            StatusColors overdueSC = new Data.StatusColors();
            overdueSC.StatusCode = "OVERDUE";
            overdueSC.ColorCode = "#FF5722";
            overdueSC.HotelId = hotel.HotelId;
            overdueSC.DefaultColorCode = "#FF5722";
            context.StatusColors.InsertOnSubmit(overdueSC);

            StatusColors repairSC = new Data.StatusColors();
            repairSC.StatusCode = "REPAIR";
            //repairSC.ColorCode = "#E6E6FA";
            repairSC.ColorCode = "#607D8B";
            repairSC.HotelId = hotel.HotelId;
            //repairSC.DefaultColorCode = "#E6E6FA";
            repairSC.DefaultColorCode = "#607D8B";
            context.StatusColors.InsertOnSubmit(repairSC);

            StatusColors dirtySC = new Data.StatusColors();
            dirtySC.StatusCode = "DIRTY";
            dirtySC.ColorCode = "#D2B48C";
            dirtySC.HotelId = hotel.HotelId;
            dirtySC.DefaultColorCode = "#D2B48C";
            context.StatusColors.InsertOnSubmit(dirtySC);

            StatusColors noShowSC = new Data.StatusColors();
            noShowSC.StatusCode = "NOSHOW";
            noShowSC.ColorCode = "#9C27B0";
            noShowSC.HotelId = hotel.HotelId;
            noShowSC.DefaultColorCode = "#9C27B0";
            context.StatusColors.InsertOnSubmit(noShowSC);

            RoomPrices defaultPlan = new Data.RoomPrices();
            defaultPlan.RoomPriceName = "DEFAULT_PLAN";
            defaultPlan.FullDayPrice = standardRoomType.Price;
            defaultPlan.UseFullDayPrice = true;
            defaultPlan.StartDate = (DateTime)SqlDateTime.MinValue;
            defaultPlan.EndDate = (DateTime)SqlDateTime.MaxValue;
            defaultPlan.ApplyOnMonday = true;
            defaultPlan.ApplyOnTuesday = true;
            defaultPlan.ApplyOnWednesday = true;
            defaultPlan.ApplyOnThursday = true;
            defaultPlan.ApplyOnFriday = true;
            defaultPlan.ApplyOnSaturday = true;
            defaultPlan.ApplyOnSunday = true;
            defaultPlan.HotelId = hotel.HotelId;
            defaultPlan.RoomTypeId = standardRoomType.RoomTypeId;
            defaultPlan.IsActive = true;
            defaultPlan.FullDayCheckoutTime = new TimeSpan(12, 0, 0);
            context.RoomPrices.InsertOnSubmit(defaultPlan);

            // set default for invoice
            HotelForm hotelFormInvoice = new HotelForm();
            hotelFormInvoice.HotelId = hotel.HotelId;
            hotelFormInvoice.FormType = "RoomInvoice";
            hotelFormInvoice.Value = "A4";
            context.HotelForm.InsertOnSubmit(hotelFormInvoice);

            HotelForm hotelFormReceipt = new HotelForm();

            hotelFormReceipt.HotelId = hotel.HotelId;
            hotelFormReceipt.FormType = "Receipt";
            hotelFormReceipt.Value = "A4";
            context.HotelForm.InsertOnSubmit(hotelFormReceipt);

            context.SubmitChanges();



            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            // Create new ezAccount
            EzAccounts account = new EzAccounts();
            account.HotelId = hotel.HotelId;
            account.Amount = 0.0M;
            account.AmountFee = 0.0M;
            context.EzAccounts.InsertOnSubmit(account);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            var defaultDiscount = context.EzDefaultDiscounts.Where(dis => dis.EzDefaultDiscountId == dis.EzDefaultDiscountId && dis.Status==true).ToList();
            if (defaultDiscount.Count > 0)
            {
                foreach (var discount in defaultDiscount)
                {
                    EzHotelDefaultDiscounts hotelDefaultDiscount = new EzHotelDefaultDiscounts();
                    hotelDefaultDiscount.HotelId = hotel.HotelId;
                    hotelDefaultDiscount.EzDefaultDiscountId = discount.EzDefaultDiscountId;
                    hotelDefaultDiscount.StartDate = hotel.CreatedDate;
                    hotelDefaultDiscount.EndDate = hotel.CreatedDate.Value.AddDays((double)discount.TotalDayFee);
                    context.EzHotelDefaultDiscounts.InsertOnSubmit(hotelDefaultDiscount);
                }
                context.SubmitChanges();
                Common.Elastic.IndexLastAudit(context);
            }

            var ezModule = context.EzModules.Where(m => m.DefaultStatus == true && m.Status == true).ToList();
            if (ezModule.Count > 0)
            {
                foreach (var item in ezModule)
                {
                    EzHotelModules ezHotelModule = new EzHotelModules();
                    ezHotelModule.HotelId = hotel.HotelId;
                    ezHotelModule.Status = true;
                    ezHotelModule.EzModuleId = item.EzModuleId;

                    context.EzHotelModules.InsertOnSubmit(ezHotelModule);
                    context.SubmitChanges();

                    EzHotelModuleLogs ezHotelModuleLog = new EzHotelModuleLogs();
                    ezHotelModuleLog.EzHotelModuleId = ezHotelModule.EzHotelModuleId;
                    ezHotelModuleLog.Status = true;
                    ezHotelModuleLog.CreateDate = DateTime.UtcNow; ;
                    context.EzHotelModuleLogs.InsertOnSubmit(ezHotelModuleLog);
                    context.SubmitChanges();
                }
                //context.SubmitChanges();
                Common.Elastic.IndexLastAudit(context);
            }

            //ROOM HISTORY
            var roomList = context.Rooms.Where(rm => rm.HotelId == hotel.HotelId).ToList();
            var roomActiveHistory = new List<RoomActiveHistory>();
            foreach (var room in roomList)
            {
                var roomAH = new RoomActiveHistory()
                {
                    HotelId = hotel.HotelId,
                    RoomId = room.RoomId,
                    Date = room.CreatedDate,
                    Status = "ACTIVE"
                };
                roomActiveHistory.Add(roomAH);
            }
            context.RoomActiveHistory.InsertAllOnSubmit(roomActiveHistory);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            // HotelDisplays
            var hotelDisplays = new HotelDisplays();
            hotelDisplays.HotelId = hotel.HotelId;
            hotelDisplays.DisplayGroupDetailId = 4;
            hotelDisplays.DisplayGroupId = 2;
            hotelDisplays.DisplayGroupPriority = 1;
            hotelDisplays.DisplayGroupDetailPriority = 1;

            context.HotelDisplays.InsertOnSubmit(hotelDisplays);
           

            hotelDisplays = new HotelDisplays();
            hotelDisplays.HotelId = hotel.HotelId;
            hotelDisplays.DisplayGroupDetailId = 5;
            hotelDisplays.DisplayGroupId = 1;
            hotelDisplays.DisplayGroupPriority = 2;
            hotelDisplays.DisplayGroupDetailPriority = 1;
            context.HotelDisplays.InsertOnSubmit(hotelDisplays);
           

            hotelDisplays = new HotelDisplays();
            hotelDisplays.HotelId = hotel.HotelId;
            hotelDisplays.DisplayGroupDetailId = 15;
            hotelDisplays.DisplayGroupId = 4;
            hotelDisplays.DisplayGroupPriority = 4;
            hotelDisplays.DisplayGroupDetailPriority = 1;

            context.HotelDisplays.InsertOnSubmit(hotelDisplays);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);


            //HotelAppCode Config default
            var hotelAppCodeList = context.HotelAppCode.Where(rm => rm.HotelAppCodeType == "NOTIFICATION").ToList();
            var hotelAppConfigList = new List<HotelAppConfig>();
            foreach (var appcode in hotelAppCodeList)
            {
                var hotelAppConfigRow = new HotelAppConfig()
                {
                    HotelId = hotel.HotelId,
                    HotelAppCodeId = appcode.HotelAppCodeId
                };
                hotelAppConfigList.Add(hotelAppConfigRow);
            }
            context.HotelAppConfig.InsertAllOnSubmit(hotelAppConfigList);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            // Add Maket default

            var market = new Market();
            market.MarketCode = "ASIA";
            market.MarketName = "Châu á";
            market.IsAvailable = true;
            market.CreatedDate = DateTime.UtcNow;
            market.CreatedUserId = currentClientUser.UserId;
            market.HotelId = hotel.HotelId;
            market.Priority = 1;
            context.Market.InsertOnSubmit(market);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            //Add Source default
            var sourceList = new List<Source>();
            var source = new Source();
            source.ShortCode = "ONLINE";
            source.SourceName = "ONLINE";
            source.IsAvailable = true;
            source.CreatedDate = DateTime.UtcNow;
            source.CreatedUserId = currentClientUser.UserId;
            source.HotelId = hotel.HotelId;
            source.Priority = 1;
            sourceList.Add(source);

            var source1 = new Source();
            source1.ShortCode = "COMPANY";
            source1.SourceName = "Công ty";
            source1.IsAvailable = true;
            source1.CreatedDate = DateTime.UtcNow;
            source1.CreatedUserId = currentClientUser.UserId;
            source1.HotelId = hotel.HotelId;
            source1.Priority = 2;
            sourceList.Add(source1);

            var source2 = new Source();

            source2.ShortCode = "WALKIN";
            source2.SourceName = "WALK-IN";
            source2.IsAvailable = true;
            source2.CreatedDate = DateTime.UtcNow;
            source2.CreatedUserId = currentClientUser.UserId;
            source2.HotelId = hotel.HotelId;
            source2.Priority = 3;
            sourceList.Add(source2);

            context.Source.InsertAllOnSubmit(sourceList);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            var source4 = context.Source.Where(s => s.HotelId == hotel.HotelId && s.ShortCode == "COMPANY").FirstOrDefault();

            var company = new Company();
            company.CompanyName = "CÔNG TY CP CÔNG NGHỆ EZCLOUD TOÀN CẦU";
            company.CompanyCode = "ezcloud";
            company.CompanyPhone = "(+84)1900 6159";
            company.CompanyEmail = "sale@ezcloud.vn";
            company.ContactName = "Sale";
            company.ContactMobile = "(+84) 904 17 1080";
            company.IsAvailable = true;
            company.CreatedDate = DateTime.UtcNow;
            company.CreatedUserId = currentClientUser.UserId;
            company.HotelId = hotel.HotelId;
            if (source4 != null) company.SourceId = source4.SourceId;

            context.Company.InsertOnSubmit(company);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            //EmailSender.SendEmailHotelExpiredDateCountDown(hotel.HotelOwnerAspNetUsers.Email, "ezCloud Hotel - Tình trạng thời gian sử dụng khách sạn / remaining time for hotel: " + hotel.HotelName, hotel.HotelOwnerAspNetUsers.Email, hotel.RemainingDays.ToString());
            var hotelDiscount = context.EzHotelDefaultDiscounts.Where(h => h.HotelId == hotel.HotelId)
                      .Join(context.EzDefaultDiscounts.Where(p => p.DiscountCode == "ROOM"), lv => lv.EzDefaultDiscountId, lv1 => lv1.EzDefaultDiscountId, (lv, lv1) => new { lv.StartDate, lv.EndDate }).FirstOrDefault();
            if (hotelDiscount != null)
            {
                string subjec = "ezCloudHotel.com - Trial period for hotel / Thông báo thời hạn sử dụng phần mềm: " + hotel.HotelName.ToString() + "(Hotel ID: " + hotel.HotelId.ToString() + ")";
                EmailSender.SendEmailCreatedHotel(hotel.HotelOwnerAspNetUsers.Email,subjec, hotel.HotelOwnerAspNetUsers.Email, hotel.HotelId, hotel.HotelName, (DateTime)hotelDiscount.StartDate, (DateTime)hotelDiscount.EndDate);
            }
            return Ok(hotel);
        }

        
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("SystemInfo")]
        public async Task<IHttpActionResult> SystemInfo()
        {
            ReadOnlyCollection<TimeZoneInfo> tz;
            tz = TimeZoneInfo.GetSystemTimeZones();
            var currencies = context.Currencies.Where(curr => curr.CurrencyId == curr.CurrencyId).ToList();
            return Ok(new
            {
                TimeZones  = tz,
                Currencies = currencies
            });
        }

        public class DemoHotelModel
        {
            public int CurrencyId { get; set; }
            public string TimeZoneId { get; set; }
        }
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("CreateDemoHotel")]
        public async Task<IHttpActionResult> CreateDemoHotel(DemoHotelModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var currentClientUser = Common.UserUtitily.getUserProfile();

            //Tạo mới khách sạn
            Hotels hotel = new Data.Hotels();
            hotel.HotelEmail = "hotro@ezcloud.vn";
            hotel.HotelName = "Demo Hotel";
            hotel.HotelAddress = "266 Đội Cấn, Ba Đình, Hà Nội";
            hotel.HotelPhone = "19006159";
            hotel.EzCloudSubdomain = null;
            hotel.HotelDomain = null;
            hotel.HotelWebsite = "http://ezcloud.vn/";
            hotel.HotelLogoUrl = null;
            hotel.HotelSizeId = null;
            hotel.IsActive = true;
            hotel.ExpireDate = DateTime.UtcNow.AddDays(30);
            hotel.FullDayCheckoutTime = new TimeSpan(12, 0, 0);
            hotel.FullDayCheckinTime = new TimeSpan(12, 0, 0);
            hotel.TimeInPrivate = new TimeSpan(14, 0, 0);
            hotel.TimeOutPrivate = new TimeSpan(12, 0, 0);
            hotel.DayNightStartTime = new TimeSpan(21, 0, 0);
            hotel.DayNightEndTime = new TimeSpan(12, 0, 0);
            hotel.NightAuditTime = new TimeSpan(0, 0, 0);
            hotel.CreatedDate = DateTime.UtcNow;
            hotel.ExpireDate = hotel.CreatedDate.HasValue ? hotel.CreatedDate.Value.AddMonths(3) : (DateTime?)null;
            hotel.IsRoomDirtyAfterNighAudit = true;
            hotel.RemainingDays = 0;
            //hotel.TimeZoneId = "SE Asia Standard Time";
            //hotel.TimeZoneOffset = 420;

            hotel.TimeZoneId = model.TimeZoneId;
            var offSet = TimeZoneInfo.FindSystemTimeZoneById(model.TimeZoneId);
            hotel.TimeZoneOffset = (int)offSet.BaseUtcOffset.TotalMinutes;

            

            var user = UserManager.FindByName(currentClientUser.UserName);
            hotel.HotelOwnerId = currentClientUser.UserId;
            context.Hotels.InsertOnSubmit(hotel);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);
             var currency = context.Currencies.Where(curr => curr.CurrencyId == model.CurrencyId).FirstOrDefault();
            Money defaultMoney = new Data.Money();
            defaultMoney.MoneyName = currency.AlphabeticCode;
            defaultMoney.ExchangeRate = 1.00;
            defaultMoney.HotelId = hotel.HotelId;
            defaultMoney.CurrencyId = currency.CurrencyId;
            context.Money.InsertOnSubmit(defaultMoney);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);
            hotel.DefaultMoneyId = defaultMoney.MoneyId;

            //Gán lại defaultHotelId cho User
            user.DefaultHotelId = hotel.HotelId;
            UserManager.Update(user);

            //Tạo loại phòng mặc định (Standard Room)
            RoomTypes singleRoomType = new Data.RoomTypes();
            singleRoomType.DefaultAdults = 1;
            singleRoomType.DefaultChilds = 0;
            singleRoomType.RoomTypeName = "SINGLE";
            singleRoomType.RoomTypeCode = "STD";
            singleRoomType.RoomTypeDescription = "SINGLE";
            singleRoomType.HotelId = hotel.HotelId;
            singleRoomType.Price =currency.AlphabeticCode=="VND"? 350000:16;
            context.RoomTypes.InsertOnSubmit(singleRoomType);

            RoomTypes doubleRoomType = new Data.RoomTypes();
            doubleRoomType.DefaultAdults = 1;
            doubleRoomType.DefaultChilds = 0;
            doubleRoomType.RoomTypeName = "DOUBLE";
            doubleRoomType.RoomTypeCode = "DBL";
            doubleRoomType.RoomTypeDescription = "DOUBLE";
            doubleRoomType.HotelId = hotel.HotelId;
            doubleRoomType.Price = currency.AlphabeticCode == "VND" ? 700000 : 32;
            context.RoomTypes.InsertOnSubmit(doubleRoomType);
            //Tạo tầng 
            var listFloor = new List<Floors>();
            for (int i = 0; i < 4; i++)
            {
                Floors floor = new Floors();
                floor.CreatedDate = DateTime.UtcNow;
                floor.CreatedUserId = currentClientUser.UserId;
                floor.HotelId = hotel.HotelId;
                floor.OrderNumber = (i + 1);
                floor.IsDeleted = false;
                floor.IsActive = true;
                floor.FloorName = "FLOOR " + (i + 1).ToString();
                listFloor.Add(floor);
            };
            context.Floors.InsertAllOnSubmit(listFloor);

            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

           
            //Tạo Danh sách phòng mặc định
            var listRoom = new List<Rooms>();
            int roomTypeId;
            for (int i = 0; i < 4; i++)
            {
                roomTypeId = singleRoomType.RoomTypeId; 
                if(i > 1)
                {
                    roomTypeId = doubleRoomType.RoomTypeId;
                }
                var floor = listFloor[i];
                for (int j = 0; j < 5; j++)
                {
                    Rooms room = new Rooms();
                    //room.RoomLocation = "FLOOR " + (i + 1);
                    if (floor.FloorId != null)
                    {
                        room.FloorId = floor.FloorId;
                    }
                    room.RoomDescription = "ROOM " + (i + 1) + "0" + (j + 1);
                    room.HotelId = hotel.HotelId;
                    room.RoomTypeId = roomTypeId;
                    room.HouseStatus = null;
                    if (j < 9)
                    {
                        room.RoomName = (i + 1) + "0" + (j + 1);
                    }
                    else
                    {
                        room.RoomName = (i + 1).ToString() + (j + 1).ToString();
                    }
                    room.CreatedDate = DateTime.UtcNow;
                    room.CreatedUserId = user.Id;
                    room.Priority = listRoom.Count;
                    listRoom.Add(room);
                    context.Rooms.InsertOnSubmit(room);

                }
            }
            context.Rooms.InsertAllOnSubmit(listRoom);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            //Tạo extra service types mặc định
            string[] esTypesName = new string[] {
                                                    "MINIBAR",
                                                    "LAUNDRY",
                                                    "EXTRA_ROOM_CHARGE",
                                                    "COMPENSATION",
                                                    "EXTRA_SERVICES"
                                                };
            string[] esTypesDescription = new string[] {
                                                            "Minibar",
                                                            "Laundry",
                                                            "ExtraRoomCharge",
                                                            "Compensation",
                                                            "ExtraServices"
                                                       };

            List<List<string>> esCategoryName = new List<List<string>>();
            List<List<string>> esCategoryDescription = new List<List<string>>();

            //MiniBar
            List<string> miniBarCategoryName = new List<String> { "DRINK", "FOOD" };
            esCategoryName.Add(miniBarCategoryName);
            List<string> miniBarCategoryDescription = new List<String> { "DRINK", "FOOD" };
            esCategoryDescription.Add(miniBarCategoryDescription);

            //Laundry
            List<string> laundryCategoryName = new List<String> { "DRY_CLEANING", "WASH_AND_IRON" };
            esCategoryName.Add(laundryCategoryName);
            List<string> laundryCategoryDescription = new List<String> { "DRY_CLEANING", "WASH_AND_IRON" };
            esCategoryDescription.Add(laundryCategoryDescription);

            //ExtraRoomCharge
            List<string> extraRoomChargeCategoryName = new List<String> { };
            esCategoryName.Add(extraRoomChargeCategoryName);
            List<string> extraRoomChargeCategoryDescription = new List<String> { };
            esCategoryDescription.Add(extraRoomChargeCategoryDescription);

            //Compensation
            List<string> compensationCategoryName = new List<String> { "AMENITY_COMPENSATION" };
            esCategoryName.Add(compensationCategoryName);
            List<string> compensationCategoryDescription = new List<String> { "AMENITY_COMPENSATION" };
            esCategoryDescription.Add(compensationCategoryDescription);

            //ExtraServies
            List<string> extraServiesCategoryName = new List<String>();
            esCategoryName.Add(extraServiesCategoryName);
            List<string> extraServiesCategoryDescription = new List<String>();
            esCategoryDescription.Add(extraServiesCategoryDescription);

            //Extra Service Item
            List<EsItem> drinkItems = new List<EsItem>
            {
                new EsItem{
                    ExtraServiceItemName = "Bia Sài Gòn Đỏ",
                    Price =currency.AlphabeticCode == "VND" ? 14000 : (decimal)(0.8),
                    Unit = "chai"
                },
                new EsItem{
                    ExtraServiceItemName = "Bia Ken",
                    Price = currency.AlphabeticCode == "VND" ? 20000 : (decimal)(0.9),
                    Unit = "chai"
                },
                new EsItem{
                    ExtraServiceItemName = "Bia Ken lon",
                    Price = currency.AlphabeticCode == "VND" ? 22000 : (decimal)(1.2),
                    Unit = "lon"
                },
                new EsItem{
                    ExtraServiceItemName = "Bia  Sài Gòn Xanh",
                    Price = currency.AlphabeticCode == "VND" ? 16000 : (decimal)(0.9),
                    Unit = "lon"
                },
                 new EsItem{
                    ExtraServiceItemName = "Nước ngọt ",
                    Price = currency.AlphabeticCode == "VND" ? 15000 : (decimal)(0.6),
                    Unit = "lon"
                },
            };

            List<EsItem> foodItems = new List<EsItem>
            {
                new EsItem{
                    ExtraServiceItemName = "Kẹo Gum",
                    Price = currency.AlphabeticCode == "VND" ? 5000 : (decimal)(0.2),
                    Unit = "thẻ"
                },
                new EsItem{
                    ExtraServiceItemName = "Phồng tôm",
                    Price = currency.AlphabeticCode == "VND" ? 20000 : (decimal)(0.95),
                    Unit = "gói"
                },
                new EsItem
                {
                    ExtraServiceItemName = "Mít sấy",
                    Price = currency.AlphabeticCode == "VND" ? 45000 : (decimal)(3.2),
                    Unit = "gói"
                }
            };

            List<EsItem> dryCleaningItems = new List<EsItem>
            {
                new EsItem{
                    ExtraServiceItemName = "Áo sơ mi",
                    Price = currency.AlphabeticCode == "VND" ? 5000 : (decimal)(0.2),
                    Unit = "Cái"
                },
                new EsItem{
                    ExtraServiceItemName = "Áo phông",
                    Price = currency.AlphabeticCode == "VND" ? 4000 : (decimal)(0.1),
                    Unit = "Cái"
                },
                new EsItem
                {
                    ExtraServiceItemName = "Áo khoác",
                    Price = currency.AlphabeticCode == "VND" ? 7000 : (decimal)(0.3),
                    Unit = "Cái"
                }
            };

            List<EsItem> washAndIronItems = new List<EsItem>
            {
                new EsItem{
                    ExtraServiceItemName = "Áo sơ mi",
                    Price = currency.AlphabeticCode == "VND" ? 8000 : (decimal)(0.4),
                    Unit = "Cái"
                },
                new EsItem{
                    ExtraServiceItemName = "Áo phông",
                    Price = currency.AlphabeticCode == "VND" ? 6000 : (decimal)(0.4),
                    Unit = "Cái"
                },
                new EsItem
                {
                    ExtraServiceItemName = "Áo khoác",
                    Price = currency.AlphabeticCode == "VND" ? 12000 : (decimal)(0.6),
                    Unit = "Cái"
                }
            };

            List<EsItem> amenityCompensationItems = new List<EsItem>
            {
                new EsItem{
                    ExtraServiceItemName = "Khăn mặt",
                    Price = currency.AlphabeticCode == "VND" ? 30000 : (decimal)(1.2),
                    Unit = "Cái"
                },
                new EsItem{
                    ExtraServiceItemName = "Khăn tắm",
                    Price = currency.AlphabeticCode == "VND" ? 180000 : (decimal)(8.3),
                    Unit = "Cái"
                },
                new EsItem
                {
                    ExtraServiceItemName = "Thảm chùi chân",
                    Price = currency.AlphabeticCode == "VND" ? 45000 : (decimal)(2.09),
                    Unit = "Cái"
                }
            };


            for (int i = 0; i < esTypesName.Length; i++)
            {
                ExtraServiceTypes esTypes = new Data.ExtraServiceTypes();
                esTypes.ExtraServiceTypeName = esTypesName[i];
                esTypes.ExtraServiceDescription = esTypesDescription[i];
                esTypes.HotelId = hotel.HotelId;
                context.ExtraServiceTypes.InsertOnSubmit(esTypes);
                context.SubmitChanges();
                Common.Elastic.IndexLastAudit(context);
                if (i < esCategoryName.Count)
                {
                    List<string> categoriesNameByTypes = new List<string>(esCategoryName[i]);
                    List<string> categoriesDescriptionByTypes = new List<string>(esCategoryDescription[i]);
                    for (int j = 0; j < categoriesNameByTypes.Count; j++)
                    {
                        ExtraServiceCategories esCategories = new Data.ExtraServiceCategories();
                        esCategories.ExtraServiceCategoryName = categoriesNameByTypes[j];
                        esCategories.ExtraServiceCategoryDescription = categoriesDescriptionByTypes[j];
                        esCategories.ExtraServiceTypeId = esTypes.ExtraServiceTypeId;
                        esCategories.HotelId = hotel.HotelId;
                        context.ExtraServiceCategories.InsertOnSubmit(esCategories);
                        context.SubmitChanges();
                        Common.Elastic.IndexLastAudit(context);
                        if (esTypes.ExtraServiceTypeName == "MINIBAR")
                        {
                            if (esCategories.ExtraServiceCategoryName == "DRINK")
                            {
                                if (drinkItems.Count > 0)
                                {
                                    for (int drinkIndex = 0; drinkIndex < drinkItems.Count; drinkIndex++)
                                    {
                                        ExtraServiceItems esItem = new ExtraServiceItems();
                                        esItem.ExtraServiceItemName = drinkItems[drinkIndex].ExtraServiceItemName;
                                        esItem.Price = drinkItems[drinkIndex].Price;
                                        esItem.Unit = drinkItems[drinkIndex].Unit;
                                        esItem.HotelId = hotel.HotelId;
                                        esItem.ExtraServiceCategoryId = esCategories.ExtraServiceCategoryId;
                                        esItem.ExtraServiceTypeId = esTypes.ExtraServiceTypeId;
                                        context.ExtraServiceItems.InsertOnSubmit(esItem);
                                    }
                                    context.SubmitChanges();
                                    Common.Elastic.IndexLastAudit(context);
                                }
                            }
                            if (esCategories.ExtraServiceCategoryName == "FOOD")
                            {
                                if (foodItems.Count > 0)
                                {
                                    for (int foodIndex = 0; foodIndex < foodItems.Count; foodIndex++)
                                    {
                                        ExtraServiceItems esItem = new ExtraServiceItems();
                                        esItem.ExtraServiceItemName = foodItems[foodIndex].ExtraServiceItemName;
                                        esItem.Price = foodItems[foodIndex].Price;
                                        esItem.Unit = foodItems[foodIndex].Unit;
                                        esItem.HotelId = hotel.HotelId;
                                        esItem.ExtraServiceCategoryId = esCategories.ExtraServiceCategoryId;
                                        esItem.ExtraServiceTypeId = esTypes.ExtraServiceTypeId;
                                        context.ExtraServiceItems.InsertOnSubmit(esItem);
                                    }
                                    context.SubmitChanges();
                                    Common.Elastic.IndexLastAudit(context);
                                }
                            }
                        }
                        if (esTypes.ExtraServiceTypeName == "LAUNDRY")
                        {
                            if (esCategories.ExtraServiceCategoryName == "DRY_CLEANING")
                            {
                                if (dryCleaningItems.Count > 0)
                                {
                                    for (int dryCleaningIndex = 0; dryCleaningIndex < dryCleaningItems.Count; dryCleaningIndex++)
                                    {
                                        ExtraServiceItems esItem = new ExtraServiceItems();
                                        esItem.ExtraServiceItemName = dryCleaningItems[dryCleaningIndex].ExtraServiceItemName;
                                        esItem.Price = dryCleaningItems[dryCleaningIndex].Price;
                                        esItem.Unit = dryCleaningItems[dryCleaningIndex].Unit;
                                        esItem.HotelId = hotel.HotelId;
                                        esItem.ExtraServiceCategoryId = esCategories.ExtraServiceCategoryId;
                                        esItem.ExtraServiceTypeId = esTypes.ExtraServiceTypeId;
                                        context.ExtraServiceItems.InsertOnSubmit(esItem);
                                    }
                                    context.SubmitChanges();
                                    Common.Elastic.IndexLastAudit(context);
                                }
                            }
                            if (esCategories.ExtraServiceCategoryName == "WASH_AND_IRON")
                            {
                                if (washAndIronItems.Count > 0)
                                {
                                    for (int amenityCompensationIndex = 0; amenityCompensationIndex < washAndIronItems.Count; amenityCompensationIndex++)
                                    {
                                        ExtraServiceItems esItem = new ExtraServiceItems();
                                        esItem.ExtraServiceItemName = washAndIronItems[amenityCompensationIndex].ExtraServiceItemName;
                                        esItem.Price = washAndIronItems[amenityCompensationIndex].Price;
                                        esItem.Unit = washAndIronItems[amenityCompensationIndex].Unit;
                                        esItem.HotelId = hotel.HotelId;
                                        esItem.ExtraServiceCategoryId = esCategories.ExtraServiceCategoryId;
                                        esItem.ExtraServiceTypeId = esTypes.ExtraServiceTypeId;
                                        context.ExtraServiceItems.InsertOnSubmit(esItem);
                                    }
                                    context.SubmitChanges();
                                    Common.Elastic.IndexLastAudit(context);
                                }
                            }
                        }
                        if (esTypes.ExtraServiceTypeName == "COMPENSATION")
                        {
                            if (esCategories.ExtraServiceCategoryName == "AMENITY_COMPENSATION")
                            {
                                if (amenityCompensationItems.Count > 0)
                                {
                                    for (int amenityCompensationIndex = 0; amenityCompensationIndex < amenityCompensationItems.Count; amenityCompensationIndex++)
                                    {
                                        ExtraServiceItems esItem = new ExtraServiceItems();
                                        esItem.ExtraServiceItemName = amenityCompensationItems[amenityCompensationIndex].ExtraServiceItemName;
                                        esItem.Price = amenityCompensationItems[amenityCompensationIndex].Price;
                                        esItem.Unit = amenityCompensationItems[amenityCompensationIndex].Unit;
                                        esItem.HotelId = hotel.HotelId;
                                        esItem.ExtraServiceCategoryId = esCategories.ExtraServiceCategoryId;
                                        esItem.ExtraServiceTypeId = esTypes.ExtraServiceTypeId;
                                        context.ExtraServiceItems.InsertOnSubmit(esItem);
                                    }
                                    context.SubmitChanges();
                                    Common.Elastic.IndexLastAudit(context);
                                }
                            }
                        }
                    }
                }


            }

           

            StatusColors availableSC = new Data.StatusColors();
            availableSC.StatusCode = "AVAILABLE";
            availableSC.ColorCode = "#43A047";
            availableSC.HotelId = hotel.HotelId;
            availableSC.DefaultColorCode = "#43A047";
            context.StatusColors.InsertOnSubmit(availableSC);

            StatusColors bookedSC = new Data.StatusColors();
            bookedSC.StatusCode = "BOOKED";
            bookedSC.ColorCode = "#1E88E5";
            bookedSC.HotelId = hotel.HotelId;
            bookedSC.DefaultColorCode = "#1E88E5";
            context.StatusColors.InsertOnSubmit(bookedSC);

            StatusColors checkInSC = new Data.StatusColors();
            checkInSC.StatusCode = "CHECKIN";
            checkInSC.ColorCode = "#EF5350";
            checkInSC.HotelId = hotel.HotelId;
            checkInSC.DefaultColorCode = "#EF5350";
            context.StatusColors.InsertOnSubmit(checkInSC);

            StatusColors checkOutSC = new Data.StatusColors();
            checkOutSC.StatusCode = "CHECKOUT";

            checkOutSC.ColorCode = "#EE82EE";
            checkOutSC.HotelId = hotel.HotelId;
            checkOutSC.DefaultColorCode = "#EE82EE";
            context.StatusColors.InsertOnSubmit(checkOutSC);

            StatusColors cancelledSC = new Data.StatusColors();
            cancelledSC.StatusCode = "CANCELLED";
            cancelledSC.ColorCode = "#808080";
            cancelledSC.HotelId = hotel.HotelId;
            cancelledSC.DefaultColorCode = "#808080";
            context.StatusColors.InsertOnSubmit(cancelledSC);

            StatusColors overdueSC = new Data.StatusColors();
            overdueSC.StatusCode = "OVERDUE";
            overdueSC.ColorCode = "#FF5722";
            overdueSC.HotelId = hotel.HotelId;
            overdueSC.DefaultColorCode = "#FF5722";
            context.StatusColors.InsertOnSubmit(overdueSC);

            StatusColors repairSC = new Data.StatusColors();
            repairSC.StatusCode = "REPAIR";
            //repairSC.ColorCode = "#E6E6FA";
            repairSC.ColorCode = "#607D8B";
            repairSC.HotelId = hotel.HotelId;
            //repairSC.DefaultColorCode = "#E6E6FA";
            repairSC.DefaultColorCode = "#607D8B";
            context.StatusColors.InsertOnSubmit(repairSC);

            StatusColors dirtySC = new Data.StatusColors();
            dirtySC.StatusCode = "DIRTY";
            dirtySC.ColorCode = "#D2B48C";
            dirtySC.HotelId = hotel.HotelId;
            dirtySC.DefaultColorCode = "#D2B48C";
            context.StatusColors.InsertOnSubmit(dirtySC);

            StatusColors noShowSC = new Data.StatusColors();
            noShowSC.StatusCode = "NOSHOW";
            noShowSC.ColorCode = "#9C27B0";
            noShowSC.HotelId = hotel.HotelId;
            noShowSC.DefaultColorCode = "#9C27B0";
            context.StatusColors.InsertOnSubmit(noShowSC);

            RoomPrices singlePlan = new Data.RoomPrices();
            singlePlan.RoomPriceName = "SINGLE_RATE";
            singlePlan.FullDayPrice = currency.AlphabeticCode == "VND" ? 350000 : 16;
            singlePlan.UseFullDayPrice = true;
            singlePlan.UseDayNightPrice = true;
            singlePlan.DayNightPrice = currency.AlphabeticCode == "VND" ? 250000 : (decimal)(14.62); 
            singlePlan.UseHourlyPrice = true;
            singlePlan.UseExtraAdultPrice = true;
            singlePlan.DefaultAdults = 1;
            singlePlan.DefaultChildren = 0;
            singlePlan.ExtraAdultPrice = currency.AlphabeticCode == "VND" ? 100000 : (decimal)(4.65);
            singlePlan.UseExtraChildPrice = true;
            singlePlan.ExtraChildPrice = currency.AlphabeticCode == "VND" ? 50000 : (decimal)(2.3);
            singlePlan.StartDate = (DateTime)SqlDateTime.MinValue;
            singlePlan.EndDate = (DateTime)SqlDateTime.MaxValue;
            singlePlan.ApplyOnMonday = true;
            singlePlan.ApplyOnTuesday = true;
            singlePlan.ApplyOnWednesday = true;
            singlePlan.ApplyOnThursday = true;
            singlePlan.ApplyOnFriday = true;
            singlePlan.ApplyOnSaturday = true;
            singlePlan.ApplyOnSunday = true;
            singlePlan.HotelId = hotel.HotelId;
            singlePlan.RoomTypeId = singleRoomType.RoomTypeId;
            singlePlan.IsActive = true;
            singlePlan.FullDayCheckoutTime = new TimeSpan(12, 0, 0);
            context.RoomPrices.InsertOnSubmit(singlePlan);

            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            RoomPriceAdjustment singlePlanHourlyPrice = new RoomPriceAdjustment();
            singlePlanHourlyPrice.HotelId = hotel.HotelId;
            singlePlanHourlyPrice.RoomPriceId = singlePlan.RoomPriceId;
            singlePlanHourlyPrice.NumberOfHour = 1;
            singlePlanHourlyPrice.Price = currency.AlphabeticCode == "VND" ? 100000 : (decimal)(4.65); ;
            singlePlanHourlyPrice.AdjustmentCode = "HOURLY_PRICE";
            context.RoomPriceAdjustment.InsertOnSubmit(singlePlanHourlyPrice);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);
            RoomPriceAdjustment singlePlanHourlyPrice2 = new RoomPriceAdjustment();
            singlePlanHourlyPrice2.HotelId = hotel.HotelId;
            singlePlanHourlyPrice2.RoomPriceId = singlePlan.RoomPriceId;
            singlePlanHourlyPrice2.NumberOfHour = 2;
            singlePlanHourlyPrice2.Price = currency.AlphabeticCode == "VND" ? 120000 : (decimal)(5.58); ;
            singlePlanHourlyPrice2.AdjustmentCode = "HOURLY_PRICE";
            context.RoomPriceAdjustment.InsertOnSubmit(singlePlanHourlyPrice2);

            context.SubmitChanges();

            RoomPriceAdjustment singlePlanFullDayLateCheckOut = new RoomPriceAdjustment();
            singlePlanFullDayLateCheckOut.HotelId = hotel.HotelId;
            singlePlanFullDayLateCheckOut.RoomPriceId = singlePlan.RoomPriceId;
            singlePlanFullDayLateCheckOut.NumberOfHour = 1;
            singlePlanFullDayLateCheckOut.Price = currency.AlphabeticCode == "VND" ? 20000 : (decimal)(0.93);
            singlePlanFullDayLateCheckOut.AdjustmentCode = "OVERDUE_FULLDAY";
            context.RoomPriceAdjustment.InsertOnSubmit(singlePlanFullDayLateCheckOut);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);
            RoomPriceAdjustment singlePlanFullDayLateCheckOut2 = new RoomPriceAdjustment();
            singlePlanFullDayLateCheckOut2.HotelId = hotel.HotelId;
            singlePlanFullDayLateCheckOut2.RoomPriceId = singlePlan.RoomPriceId;
            singlePlanFullDayLateCheckOut2.NumberOfHour = 2;
            singlePlanFullDayLateCheckOut2.Price = currency.AlphabeticCode == "VND" ? 40000 : (decimal)(1.86);
            singlePlanFullDayLateCheckOut2.AdjustmentCode = "OVERDUE_FULLDAY";
            context.RoomPriceAdjustment.InsertOnSubmit(singlePlanFullDayLateCheckOut2);
            context.SubmitChanges();

            RoomPriceAdjustment singlePlanDayNightLateCheckOut = new RoomPriceAdjustment();
            singlePlanDayNightLateCheckOut.HotelId = hotel.HotelId;
            singlePlanDayNightLateCheckOut.RoomPriceId = singlePlan.RoomPriceId;
            singlePlanDayNightLateCheckOut.NumberOfHour = 1;
            singlePlanDayNightLateCheckOut.Price = currency.AlphabeticCode == "VND" ? 50000 : (decimal)(0.93);
            singlePlanDayNightLateCheckOut.AdjustmentCode = "OVERDUE_DAYNIGHT";
            context.RoomPriceAdjustment.InsertOnSubmit(singlePlanDayNightLateCheckOut);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);
            RoomPriceAdjustment singlePlanDayNightLateCheckOut2 = new RoomPriceAdjustment();
            singlePlanDayNightLateCheckOut2.HotelId = hotel.HotelId;
            singlePlanDayNightLateCheckOut2.RoomPriceId = singlePlan.RoomPriceId;
            singlePlanDayNightLateCheckOut2.NumberOfHour = 2;
            singlePlanDayNightLateCheckOut2.Price = currency.AlphabeticCode == "VND" ? 40000 : (decimal)(1.86);
            singlePlanDayNightLateCheckOut2.AdjustmentCode = "OVERDUE_DAYNIGHT";
            context.RoomPriceAdjustment.InsertOnSubmit(singlePlanDayNightLateCheckOut2);

            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            RoomPrices doublePlan = new Data.RoomPrices();
            doublePlan.RoomPriceName = "DOUBLE_RATE";
            doublePlan.FullDayPrice = currency.AlphabeticCode == "VND" ? 700000 : (decimal)(32.55);
            doublePlan.UseFullDayPrice = true;
            doublePlan.UseDayNightPrice = true;
            doublePlan.DayNightPrice = currency.AlphabeticCode == "VND" ? 500000 : (decimal)(23.25);
            doublePlan.UseHourlyPrice = true;
            doublePlan.DefaultAdults = 1;
            doublePlan.DefaultChildren = 0;
            doublePlan.UseExtraAdultPrice = true;
            doublePlan.ExtraAdultPrice = currency.AlphabeticCode == "VND" ? 100000 : (decimal)(4.65);
            doublePlan.UseExtraChildPrice = true;
            doublePlan.ExtraChildPrice = currency.AlphabeticCode == "VND" ? 500000 : (decimal)(23.25);
            doublePlan.StartDate = (DateTime)SqlDateTime.MinValue;
            doublePlan.EndDate = (DateTime)SqlDateTime.MaxValue;
            doublePlan.ApplyOnMonday = true;
            doublePlan.ApplyOnTuesday = true;
            doublePlan.ApplyOnWednesday = true;
            doublePlan.ApplyOnThursday = true;
            doublePlan.ApplyOnFriday = true;
            doublePlan.ApplyOnSaturday = true;
            doublePlan.ApplyOnSunday = true;
            doublePlan.HotelId = hotel.HotelId;
            doublePlan.RoomTypeId = doubleRoomType.RoomTypeId;
            doublePlan.IsActive = true;
            doublePlan.FullDayCheckoutTime = new TimeSpan(12, 0, 0);
            context.RoomPrices.InsertOnSubmit(doublePlan);

            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            RoomPriceAdjustment doublePlanHourlyPrice = new RoomPriceAdjustment();
            doublePlanHourlyPrice.HotelId = hotel.HotelId;
            doublePlanHourlyPrice.RoomPriceId = doublePlan.RoomPriceId;
            doublePlanHourlyPrice.NumberOfHour = 1;
            doublePlanHourlyPrice.Price = currency.AlphabeticCode == "VND" ? 150000 : (decimal)(6.97);
            doublePlanHourlyPrice.AdjustmentCode = "HOURLY_PRICE";
            context.RoomPriceAdjustment.InsertOnSubmit(doublePlanHourlyPrice);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);
            RoomPriceAdjustment doublePlanHourlyPrice2 = new RoomPriceAdjustment();
            doublePlanHourlyPrice2.HotelId = hotel.HotelId;
            doublePlanHourlyPrice2.RoomPriceId = doublePlan.RoomPriceId;
            doublePlanHourlyPrice2.NumberOfHour = 2;
            doublePlanHourlyPrice2.Price = currency.AlphabeticCode == "VND" ? 180000 : (decimal)(8.4);
            doublePlanHourlyPrice2.AdjustmentCode = "HOURLY_PRICE";
            context.RoomPriceAdjustment.InsertOnSubmit(doublePlanHourlyPrice2);
            context.SubmitChanges();

            RoomPriceAdjustment doublePlanFullDayLateCheckOut = new RoomPriceAdjustment();
            doublePlanFullDayLateCheckOut.HotelId = hotel.HotelId;
            doublePlanFullDayLateCheckOut.RoomPriceId = doublePlan.RoomPriceId;
            doublePlanFullDayLateCheckOut.NumberOfHour = 1;
            doublePlanFullDayLateCheckOut.Price = currency.AlphabeticCode == "VND" ? 20000 : (decimal)(0.93);
            doublePlanFullDayLateCheckOut.AdjustmentCode = "OVERDUE_FULLDAY";
            context.RoomPriceAdjustment.InsertOnSubmit(doublePlanFullDayLateCheckOut);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            RoomPriceAdjustment doublePlanFullDayLateCheckOut2 = new RoomPriceAdjustment();
            doublePlanFullDayLateCheckOut2.HotelId = hotel.HotelId;
            doublePlanFullDayLateCheckOut2.RoomPriceId = doublePlan.RoomPriceId;
            doublePlanFullDayLateCheckOut2.NumberOfHour = 2;
            doublePlanFullDayLateCheckOut2.Price = currency.AlphabeticCode == "VND" ? 40000 : (decimal)(1.86);
            doublePlanFullDayLateCheckOut2.AdjustmentCode = "OVERDUE_FULLDAY";
            context.RoomPriceAdjustment.InsertOnSubmit(doublePlanFullDayLateCheckOut2);

            context.SubmitChanges();

            RoomPriceAdjustment doublePlanDayNightLateCheckOut = new RoomPriceAdjustment();
            doublePlanDayNightLateCheckOut.HotelId = hotel.HotelId;
            doublePlanDayNightLateCheckOut.RoomPriceId = doublePlan.RoomPriceId;
            doublePlanDayNightLateCheckOut.NumberOfHour = 1;
            doublePlanDayNightLateCheckOut.Price = currency.AlphabeticCode == "VND" ? 20000 : (decimal)(0.93);
            doublePlanDayNightLateCheckOut.AdjustmentCode = "OVERDUE_DAYNIGHT";
            context.RoomPriceAdjustment.InsertOnSubmit(doublePlanDayNightLateCheckOut);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);
            RoomPriceAdjustment doublePlanDayNightLateCheckOut2 = new RoomPriceAdjustment();
            doublePlanDayNightLateCheckOut2.HotelId = hotel.HotelId;
            doublePlanDayNightLateCheckOut2.RoomPriceId = doublePlan.RoomPriceId;
            doublePlanDayNightLateCheckOut2.NumberOfHour = 2;
            doublePlanDayNightLateCheckOut2.Price = currency.AlphabeticCode == "VND" ? 40000 : (decimal)(1.86);
            doublePlanDayNightLateCheckOut2.AdjustmentCode = "OVERDUE_DAYNIGHT";
            context.RoomPriceAdjustment.InsertOnSubmit(doublePlanDayNightLateCheckOut2);


            // set default for invoice
            HotelForm hotelFormInvoice = new HotelForm();
            hotelFormInvoice.HotelId = hotel.HotelId;
            hotelFormInvoice.FormType = "RoomInvoice";
            hotelFormInvoice.Value = "A4";
            context.HotelForm.InsertOnSubmit(hotelFormInvoice);

            HotelForm hotelFormReceipt = new HotelForm();

            hotelFormReceipt.HotelId = hotel.HotelId;
            hotelFormReceipt.FormType = "Receipt";
            hotelFormReceipt.Value = "A4";
            context.HotelForm.InsertOnSubmit(hotelFormReceipt);

            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);


            // Create new ezAccount
            EzAccounts account = new EzAccounts();
            account.HotelId = hotel.HotelId;
            account.Amount = 0.0M;
            account.AmountFee = 0.0M;
            context.EzAccounts.InsertOnSubmit(account);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);


            var defaultDiscount = context.EzDefaultDiscounts.Where(dis => dis.EzDefaultDiscountId == dis.EzDefaultDiscountId && dis.Status==true).ToList();
            if (defaultDiscount.Count > 0)
            {
                foreach (var discount in defaultDiscount)
                {
                    EzHotelDefaultDiscounts hotelDefaultDiscount = new EzHotelDefaultDiscounts();
                    hotelDefaultDiscount.HotelId = hotel.HotelId;
                    hotelDefaultDiscount.EzDefaultDiscountId = discount.EzDefaultDiscountId;
                    hotelDefaultDiscount.StartDate = hotel.CreatedDate;
                    hotelDefaultDiscount.EndDate = hotel.CreatedDate.Value.AddDays((double)discount.TotalDayFee);
                    context.EzHotelDefaultDiscounts.InsertOnSubmit(hotelDefaultDiscount);
                }
                context.SubmitChanges();
                Common.Elastic.IndexLastAudit(context);
            }

            var ezModule = context.EzModules.Where(m => m.DefaultStatus == true && m.Status == true).ToList();
            if (ezModule.Count>0)
            {
                foreach (var item in ezModule)
                {
                    EzHotelModules ezHotelModule = new EzHotelModules();
                    ezHotelModule.HotelId = hotel.HotelId;
                    ezHotelModule.Status = true;
                    ezHotelModule.EzModuleId = item.EzModuleId;

                    context.EzHotelModules.InsertOnSubmit(ezHotelModule);
                    context.SubmitChanges();

                    EzHotelModuleLogs ezHotelModuleLog = new EzHotelModuleLogs();
                    ezHotelModuleLog.EzHotelModuleId = ezHotelModule.EzHotelModuleId;
                    ezHotelModuleLog.Status = true;
                    ezHotelModuleLog.CreateDate = DateTime.UtcNow; ;
                    context.EzHotelModuleLogs.InsertOnSubmit(ezHotelModuleLog);
                    context.SubmitChanges();
                }
                //context.SubmitChanges();
                Common.Elastic.IndexLastAudit(context);
            }

            //ROOM HISTORY
            var roomList = context.Rooms.Where(rm => rm.HotelId == hotel.HotelId).ToList();
            var roomActiveHistory = new List<RoomActiveHistory>();
            foreach (var room in roomList)
            {
                var roomAH = new RoomActiveHistory()
                {
                    HotelId = hotel.HotelId,
                    RoomId = room.RoomId,
                    Date = room.CreatedDate,
                    Status = "ACTIVE"
                };
                roomActiveHistory.Add(roomAH);
            }
            context.RoomActiveHistory.InsertAllOnSubmit(roomActiveHistory);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            // HotelDisplays
            var hotelDisplays = new HotelDisplays();
            hotelDisplays.HotelId = hotel.HotelId;
            hotelDisplays.DisplayGroupDetailId = 4;
            hotelDisplays.DisplayGroupId = 2;
            hotelDisplays.DisplayGroupPriority = 1;
            hotelDisplays.DisplayGroupDetailPriority = 1;

            context.HotelDisplays.InsertOnSubmit(hotelDisplays);
            //context.SubmitChanges();

            hotelDisplays = new HotelDisplays();
            hotelDisplays.HotelId = hotel.HotelId;
            hotelDisplays.DisplayGroupDetailId = 5;
            hotelDisplays.DisplayGroupId = 1;
            hotelDisplays.DisplayGroupPriority = 2;
            hotelDisplays.DisplayGroupDetailPriority = 1;
            context.HotelDisplays.InsertOnSubmit(hotelDisplays);
            //context.SubmitChanges();

            hotelDisplays = new HotelDisplays();
            hotelDisplays.HotelId = hotel.HotelId;
            hotelDisplays.DisplayGroupDetailId = 15;
            hotelDisplays.DisplayGroupId = 4;
            hotelDisplays.DisplayGroupPriority = 4;
            hotelDisplays.DisplayGroupDetailPriority = 1;

            context.HotelDisplays.InsertOnSubmit(hotelDisplays);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            //HotelAppCode Config default
            var hotelAppCodeList = context.HotelAppCode.Where(rm => rm.HotelAppCodeType == "NOTIFICATION").ToList();
            var hotelAppConfigList = new List<HotelAppConfig>();
            foreach (var appcode in hotelAppCodeList)
            {
                var hotelAppConfigRow = new HotelAppConfig()
                {
                    HotelId = hotel.HotelId,
                    HotelAppCodeId = appcode.HotelAppCodeId
                };
                hotelAppConfigList.Add(hotelAppConfigRow);
            }
            context.HotelAppConfig.InsertAllOnSubmit(hotelAppConfigList);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            // Add Maket default

            var market = new Market();
            market.MarketCode = "ASIA";
            market.MarketName = "Châu á";
            market.IsAvailable = true;
            market.CreatedDate = DateTime.UtcNow;
            market.CreatedUserId = currentClientUser.UserId;
            market.HotelId = hotel.HotelId;
            market.Priority = 1;
            context.Market.InsertOnSubmit(market);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            //Add Source default
            var sourceList = new List<Source>();
            var source = new Source();
            source.ShortCode = "ONLINE";
            source.SourceName = "ONLINE";
            source.IsAvailable = true;
            source.CreatedDate = DateTime.UtcNow;
            source.CreatedUserId = currentClientUser.UserId;
            source.HotelId = hotel.HotelId;
            source.Priority = 1;
            sourceList.Add(source);

            var source1 = new Source();
            source1.ShortCode = "COMPANY";
            source1.SourceName = "Công ty";
            source1.IsAvailable = true;
            source1.CreatedDate = DateTime.UtcNow;
            source1.CreatedUserId = currentClientUser.UserId;
            source1.HotelId = hotel.HotelId;
            source1.Priority = 2;
            sourceList.Add(source1);

            var source2 = new Source();

            source2.ShortCode = "WALKIN";
            source2.SourceName = "WALK-IN";
            source2.IsAvailable = true;
            source2.CreatedDate = DateTime.UtcNow;
            source2.CreatedUserId = currentClientUser.UserId;
            source2.HotelId = hotel.HotelId;
            source2.Priority = 3;
            sourceList.Add(source2);

            context.Source.InsertAllOnSubmit(sourceList);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            var source4 = context.Source.Where(s => s.HotelId == hotel.HotelId && s.ShortCode == "COMPANY").FirstOrDefault();

            var company = new Company();
            company.CompanyName = "CÔNG TY CP CÔNG NGHỆ EZCLOUD TOÀN CẦU";
            company.CompanyCode = "ezcloud";
            company.CompanyPhone = "(+84)1900 6159";
            company.CompanyEmail = "sale@ezcloud.vn";
            company.ContactName = "Sale";
            company.ContactMobile = "(+84) 904 17 1080";
            company.IsAvailable = true;
            company.CreatedDate = DateTime.UtcNow;
            company.CreatedUserId = currentClientUser.UserId;
            company.HotelId = hotel.HotelId;
            if (source4 != null) company.SourceId = source4.SourceId;

            context.Company.InsertOnSubmit(company);
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            var hotelDiscount = context.EzHotelDefaultDiscounts.Where(h => h.HotelId == hotel.HotelId)
                        .Join(context.EzDefaultDiscounts.Where(p => p.DiscountCode == "ROOM"), lv => lv.EzDefaultDiscountId, lv1 => lv1.EzDefaultDiscountId, (lv, lv1) => new { lv.StartDate, lv.EndDate }).FirstOrDefault();
            if (hotelDiscount!=null)
            {
                string subjec = "ezCloudHotel.com - Trial period for hotel / Thông báo thời hạn sử dụng phần mềm: " + hotel.HotelName.ToString() + "(Hotel ID: " + hotel.HotelId.ToString() + ")";
                EmailSender.SendEmailCreatedHotel(hotel.HotelOwnerAspNetUsers.Email, subjec, hotel.HotelOwnerAspNetUsers.Email, hotel.HotelId, hotel.HotelName, (DateTime)hotelDiscount.StartDate, (DateTime)hotelDiscount.EndDate);
            }
            
            return Ok(hotel);
        }

        public class EsItem
        {
            public string ExtraServiceItemName { get; set; }
            public decimal Price { get; set; }
            public string Unit { get; set; }
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("SaveHotel")]
        public async Task<IHttpActionResult> SaveHotel(HotelViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }


            var currentClientUser = Common.UserUtitily.getUserProfile();

            Hotels oldHotels = context.Hotels.Where(oh => oh.HotelId == model.HotelId).Single();
            oldHotels.HotelName = model.HotelName;
            oldHotels.HotelAddress = model.HotelAddress;
            oldHotels.HotelEmail = model.HotelEmail;
            oldHotels.HotelPhone = model.HotelPhone;
            oldHotels.HotelDomain = model.HotelDomain;
            oldHotels.HotelWebsite = model.HotelWebsite;
            oldHotels.EzCloudSubdomain = model.ezCloudSubDomain;
            oldHotels.HotelDomain = model.HotelDomain;
            oldHotels.HotelLogoUrl = model.HotelLogoUrl;
            context.SubmitChanges();
            Common.Elastic.IndexLastAudit(context);

            return Ok();
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("SetCurrentUserDefaultHotelId")]
        public async Task<IHttpActionResult> SetCurrentUserDefaultHotelId(int hotelId)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }


            var currentClientUser = Common.UserUtitily.getUserProfile();

            AspNetUsers currentUser = context.AspNetUsers.Where(usr => usr.Id == currentClientUser.UserId).FirstOrDefault();
            if (currentUser == null)
            {
                return BadRequest("Error");
            }
            List<Hotels> hotelList = context.Hotels.Where(ht => ht.HotelOwnerAspNetUsers.Id == currentClientUser.UserId).ToList();
            if (hotelList.Count > 0)
            {
                var hotel = hotelList.Where(ht => ht.HotelId == hotelId).FirstOrDefault();
                if (hotel != null)
                {
                    Common.UserUtitily.removeUserProfileCache(currentUser.UserName);
                    currentUser.DefaultHotelId = hotelId;
                    context.SubmitChanges();
                    Common.Elastic.IndexLastAudit(context);
                }
                else
                {
                    return BadRequest("THIS_HOTEL_DOESN'T_BELONG_TO_CURRENT_USER");
                }
            }
            //currentUser.DefaultHotelId = hotelId;
            //context.SubmitChanges();
            return Ok();
        }
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("Settings")]
        public async Task<IHttpActionResult> GetHotelSettings()
        {
            var user = Common.UserUtitily.getUserProfile();
            var statusColors = context.StatusColors.Where(sc => sc.HotelId == user.HotelId).ToList();
            var isModuleRoomInDiscountTime = false;
            var discountStartDate = new DateTime();
            var discountEndDate = new DateTime();
            var currency = new Currencies();
            var hotelInfo = context.Hotels.Where(h => h.HotelId == user.HotelId).FirstOrDefault();
            if (hotelInfo != null)
            {
                var ezHotelModuleRoom = hotelInfo.EzHotelModulesList.FirstOrDefault(ezm => ezm.EzModules.ModuleCode == "ROOM" && ezm.EzModules.Status == true);
                if (ezHotelModuleRoom != null)
                {
                    var ezHotelModuleDiscount = ezHotelModuleRoom.EzModules.EzDefaultDiscountsList.FirstOrDefault().EzHotelDefaultDiscountsList.FirstOrDefault(dd => dd.HotelId == user.HotelId);
                    if (ezHotelModuleDiscount != null)
                    {
                        if (ezHotelModuleDiscount.StartDate <= DateTime.UtcNow && DateTime.UtcNow <= ezHotelModuleDiscount.EndDate)
                        {
                            isModuleRoomInDiscountTime = true;
                            discountStartDate = (DateTime)ezHotelModuleDiscount.StartDate;
                            discountEndDate = (DateTime)ezHotelModuleDiscount.EndDate;
                        }
                    }
                }

                currency = hotelInfo.MoneyList.Where(mn => mn.MoneyId == hotelInfo.DefaultMoneyId).FirstOrDefault().Currencies;
            }

            return Ok(new
            {
                StatusColors = statusColors,
                Hotel = hotelInfo,
                Currency = currency,
                isModuleRoomInDiscountTime = isModuleRoomInDiscountTime,
                discountStartDate,
                discountEndDate,
                ezReferralPrograms = context.EzReferralPrograms.Where(ez => ez.EzReferralProgramCode == "REFERRALPROGRAM").FirstOrDefault()
            });

            //var user = Common.UserUtitily.getUserProfile();
            //var statusColors = context.StatusColors.Where(sc => sc.HotelId == user.HotelId).ToList();
            //var hotelInfo = context.Hotels.Where(h => h.HotelId == user.HotelId).FirstOrDefault();

            //return Ok(new { StatusColors = statusColors, Hotel = hotelInfo, Currency = hotelInfo.MoneyList.Where(mn => mn.MoneyId == hotelInfo.DefaultMoneyId).FirstOrDefault().Currencies });
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("getHotelDisplay")]
        public async Task<IHttpActionResult> getDisplays()
        {
            var currentClientUser = Common.UserUtitily.getUserProfile();
            var display = context.DisplayGroups.Select(m => new
            {
                m.DisplayGroupId,
                m.DisplayGroupCode,
                m.DisplayGroupDesc,
                List = context.DisplayGroupDetails.Where(z => z.DisplayGroupId == m.DisplayGroupId).ToList(),
            }).ToList();
            var hotelDisplay = context.DisplayGroups.Select(m => new {
                m.DisplayGroupCode,
                m.DisplayGroupDesc,
                m.DisplayGroupId,
                List = context.HotelDisplays.Where(n => n.HotelId == currentClientUser.HotelId && n.DisplayGroupId == m.DisplayGroupId).ToList(),
            }).ToList();
            var DisplayGroupDetail = context.DisplayGroupDetails.ToList();
            var tmp = new { Listdisplay = display, hotelDisplay = hotelDisplay, displayGroupDetail = DisplayGroupDetail };
            return Ok(tmp);
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("resetCache")]
        public async Task<IHttpActionResult> ProcessResetCache()
        {
            Common.Elastic.DeleteAllCache(context);

            return Ok();
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("initCodeReferralProgram")]
        [HttpGet]
        public async Task<IHttpActionResult> ProcessInitCodeReferralProgram()
        {

            var referralProgram = context.EzReferralPrograms.Where(re => re.Status == true).FirstOrDefault();
            if (referralProgram != null)
            {
                var hotelPaymented = context.EzPaymentLogs.Where(p => p.LogKey == "NEW_PAYMENT" && p.Status == 0).Select(p => new { HotelId = p.HotelId }).ToList();

                List<int> hotelIdList = new List<int>();

                foreach (var h in hotelPaymented)
                {
                    hotelIdList.Add((int)h.HotelId);
                }
                var allHotels = context.Hotels.Where(ez => hotelIdList.Contains((int)ez.HotelId)).Select(p=>new { HotelId=p.HotelId}).ToList();

                var listEzReferralCodes = new List<EzReferralCodes>();
             

                foreach (var currentHotel in allHotels)
                {


                    EzReferralCodes ezReferralCode = new EzReferralCodes();
                    ezReferralCode.CreatedDate = DateTime.UtcNow;
                    ezReferralCode.EzReferralProgramId = referralProgram.EzReferralProgramId;
                    ezReferralCode.HotelId = currentHotel.HotelId;
                    ezReferralCode.Code = ReferralProgramUltility.ReferralCodeGenerator(currentHotel.HotelId);
                    listEzReferralCodes.Add(ezReferralCode);



                }
                context.EzReferralCodes.InsertAllOnSubmit(listEzReferralCodes);
                context.SubmitChanges();

            }
            //Get
            
            return Ok();
        }

        [Route("resetHotelCache")]
        [HttpGet]
        public async Task<IHttpActionResult> ProcessResetHotelCache(int hotelId)
        {
            if (!InternalServices.isAllowed()) { return BadRequest("IP_NOT_ALLOW_EXIST:" + HttpContext.Current.Request.UserHostAddress); };

            Common.Elastic.DeleteCache(hotelId);

            return Ok();
        }

        [HttpGet]
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("TimeInOutPrivate")]
        public async Task<IHttpActionResult> TimeInOutPrivate()
        {
            var currentClientUser = Common.UserUtitily.getUserProfile();
            var HotelTimeInOut = context.Hotels.Where(m => m.HotelId == currentClientUser.HotelId).FirstOrDefault();
            var timeInOut = new
            {
                UseTimeInOutPrivate = HotelTimeInOut.IsUseTimeInOutPrivate == null ? false : HotelTimeInOut.IsUseTimeInOutPrivate,
                TimeInPrivate = HotelTimeInOut.TimeInPrivate,
                TimeOutPrivate = HotelTimeInOut.TimeOutPrivate,
            };
            return Ok(timeInOut);
        }
    }
}